import Windy from "./libs/windyV2";
import windData from "@/assets/json/wind.json";
let windy;
let timeout;

const useWindy = (map: any, mapcanvas: HTMLCanvasElement) => {
  map.on("resize", () => {
    resetWind(map, mapcanvas);
  });

  map.on("move", () => {
    resetWind(map, mapcanvas);
  });

  map.on("zoom", () => {
    resetWind(map, mapcanvas);
  });

  map.once("style.load", function () {
    resetWind(map, mapcanvas);
    map.setPaintProperty("water-fill", "fill-color", "#24293A");
  });
  windy = new Windy({ canvas: mapcanvas, data: windData });
  resetWind(map, mapcanvas);
};

const resetWind = (map: any, mapcanvas: HTMLCanvasElement) => {
  console.log("执行");

  const obj = getEventObject(map);
  const { zoomLevel, north, south, west, east, width, height } = obj;
  mapcanvas.style.display = "none";
  if (windy) {
    windy.stop();
  }
  if (timeout) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(function () {
    let particleWidth = 0.8;
    if (zoomLevel > 2) {
      particleWidth = 0.6;
    }
    if (zoomLevel > 3) {
      particleWidth = 0.4;
    }
    if (zoomLevel > 4) {
      particleWidth = 0.2;
    }
    if (zoomLevel > 5) {
      particleWidth = 0.07;
    }
    if (zoomLevel > 6) {
      particleWidth = 0.05;
    }
    console.log(particleWidth, north, south, west, east);

    mapcanvas.style.display = "initial";
    mapcanvas.width = width;
    mapcanvas.height = height;
    // // 定义边界和范围
    // const bounds = [
    //   [0, 0],
    //   [800, 600]
    // ];
    // const extent = [
    //   [-180, -90],
    //   [180, 90]
    // ];

    // // 启动模拟
    // windy.start(bounds, 800, 600, extent);
    windy.start(
      [
        [0, 0],
        [width, height]
      ],
      width,
      height,
      [
        [west, south],
        [east, north]
      ],
      { particleLineWidth: particleWidth }
    );
  }, 500);
};

const getEventObject = (map: any) => {
  const canvas = map.getCanvas();
  const dimensions = map.getBounds();

  const result = {
    width: canvas.width,
    height: canvas.height,
    north: dimensions.getNorth(),
    south: dimensions.getSouth(),
    west: dimensions.getWest(),
    east: dimensions.getEast(),
    zoomLevel: map.getZoom()
  };
  return result;
};

export { useWindy };
